import axios from 'axios';
import qs from 'qs';
import { localstorage } from './index';
import { alert } from './index';

const service = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Token': localstorage.get('token') || '',
        'Content-Type': 'application/json'
    }
})

service.interceptors.request.use(
    config => {
        // if (config.method === 'post') {
        //     config.data = qs.stringify(config.data);
        // }

        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data;
        return res;
    },
    error => {
        const { response: { status, data }} = error;
        if (status >= 400 && status < 600) {
            alert.warn(data);
        }
        return Promise.reject({ code: status, messgae: data });
    }
)

export default service;